<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!--        卡片视图区域-->
        <el-card class="box-card">
            <el-row>
                <el-col :span="7">
                    <el-input @clear="getUsersList" clearable
                              placeholder="请输入内容" v-model="queryInfo.query">
                        <el-button @click="getUsersList" icon="el-icon-search" slot="append"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button @click="addDialogVisible = true" type="primary">添加用户</el-button>
                </el-col>
            </el-row>
            <!--            用户表格区域-->
            <el-table :data="usersList" border>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态" prop="mg_state">
                    <template slot-scope="scope">
                        <el-switch @change="selectChange(scope.row)" v-model="scope.row.mg_state"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200px">
                    <template slot-scope="scope">
                        <el-button icon="el-icon-edit" size="mini" type="primary"
                                   @click="showEdit(scope.row.id)"></el-button>
                        <el-button icon="el-icon-delete" size="mini" type="danger"
                                   @click="editDelete(scope.row.id)"></el-button>
                        <el-tooltip :enterable="false" content="分配角色"
                                    effect="dark" placement="top">
                            <el-button icon="el-icon-setting"
                                  @click="setRoleRights(scope.row)"     size="mini" type="warning"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!--            分页区域-->
            <el-pagination
                    :current-page="queryInfo.pagenum"
                    :page-size="queryInfo.pagesize"
                    :page-sizes="[1, 2, 5, 10]"
                    :total="this.total"
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
                    layout="total, sizes, prev, pager, next, jumper">
            </el-pagination>
        </el-card>

        <!--        添加用户弹框-->
        <el-dialog
                :visible.sync="addDialogVisible"
                title="添加用户"
                width="50%"
                @close="addClose">
            <span class="dialog-footer" slot="footer">
                <el-form :model="addForm" :rules="addFormRules" label-width="80px" ref="addForm">
         <el-form-item label="用户名" prop="username">
             <el-input v-model="addForm.username"></el-input>
           </el-form-item>
                    <el-form-item label="密码" prop="password">
             <el-input v-model="addForm.password"></el-input>
           </el-form-item>
                    <el-form-item label="邮箱" prop="email">
             <el-input v-model="addForm.email"></el-input>
           </el-form-item>
                    <el-form-item label="手机" prop="mobile">
             <el-input v-model="addForm.mobile"></el-input>
           </el-form-item>
                </el-form>
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button @click="addReady" type="primary">确 定</el-button>
            </span>
        </el-dialog>
        <!--          修改用户弹框-->
        <el-dialog
                title="提示"
                :visible.sync="EditdialogVisible"
                width="50%" @close="editClosed">
            <span class="dialog-footer" slot="footer">
            <el-form :model="editForm" :rules="editFormRules" label-width="70px" ref="editForm">
                <el-form-item label="用户名">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <el-button @click="EditdialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editReady()">确 定</el-button>
                </span>
        </el-dialog>

        <!--        分配用户弹框-->
        <el-dialog
                title="提示"
                :visible.sync="setRoleDialogVisible"
                width="50%" @close="setRoleClose">
           <div>
               <p>当前用户是：{{userInfo.username}}</p>
               <p>当前角色是：{{userInfo.role_name}}</p>
               <p>分配新角色：
                   <el-select v-model="selectRoleId" placeholder="请选择">
                       <el-option
                               v-for="item in rolesList"
                               :key="item.id"
                               :label="item.roleName"
                               :value="item.id">
                       </el-option>
                   </el-select>
               </p>
           </div>
            <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="setRoleClick">确 定</el-button>
  </span>
        </el-dialog>

    </div>
</template>

<script>
  export default {
    name: "User",
    data() {
      //验证邮箱的正则表达式
      var checkEmail = (rule, value, cb) => {
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+/
        if (regEmail.test(value)) {
          return cb()//是一个合法的邮箱
        }
        cb(new Error('请输入合法的邮箱'))

      }

      //验证手机号的正则表达式
      var checkMobile = (rule, value, cb) => {
        //手机号验证的正则表达式
        const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
        if (regMobile.test(value)) {
          return cb()//是一个合法的邮箱
        }
        cb(new Error('请输入合法的手机号'))
      }

      return {
        //获取用户列表的参数对象
        queryInfo: {
          query: '',
          //当前的页数
          pagenum: 1,
          pagesize: 2,
        },
        //添加用户的表单数据
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: '',
        },
        addFormRules: {
          username: [{required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 3, max: 10, message: '用户名长度应在 3 到 10个字符', trigger: 'blur'}],
          password: [
            {required: true, message: '请输入用密码', trigger: 'blur'},
            {min: 6, max: 12, message: '用户名长度应在 6 到 12个字符', trigger: 'blur'}
          ],
          email: [{required: true, message: '请输入邮箱', trigger: 'blur'},
            {validator: checkEmail, trigger: 'blur'}],
          mobile: [{required: true, message: '请输入手机号', trigger: 'blur'},
            {validator: checkMobile, trigger: 'blur'}]
        },
        editFormRules: {
          email: [{required: true, message: '请输入邮箱', trigger: 'blur'},
            {validator: checkEmail, trigger: 'blur'}],
          mobile: [{required: true, message: '请输入手机号', trigger: 'blur'},
            {validator: checkMobile, trigger: 'blur'}]
        },
        usersList: [],
        total: 0,
        addDialogVisible: false,
        EditdialogVisible: false,
        setRoleDialogVisible:false,
        editForm: {},
        userInfo:{},//保存分配角色按钮的用户信息
        rolesList:[],//所有角色列表数据
        selectRoleId:''//已选中的角色ID值
      }
    },
    methods: {
      //获取用户信息数据
      async getUsersList() {
        const {data: res} = await this.$http.get('users', {params: this.queryInfo})
        if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
        this.usersList = res.data.users
        this.total = res.data.total
      },
      //监听pagesize的改变
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize
        this.getUsersList();//每次页码改变重新查询数据
      },
      //监听页码值的改变
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage
        this.getUsersList();
      },

      async selectChange(userInfo) {
        //修改后台状态值
        const {data: res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
        if (res.meta.status !== 200) {
          userInfo.mg_state = !userInfo.mg_state
          return this.$message.error('状态设置失败')
        } else {
          this.$message.success("更新状态成功")
        }
      },
      //对话框关闭触发
      addClose() {
        this.$refs.addForm.resetFields()
      },
      //修改用户弹框关闭
      editClosed() {
        this.$refs.editForm.resetFields() //重置里面由于不正确的验证的验证结果
      },
      //分配用户角色弹框的关闭
      setRoleClose(){
        this.selectRoleId = ''
        this.userInfo = {}
      },
      addReady() {
        this.$refs.addForm.validate(async valid => {
          if (!valid) return
          //成功  发起添加用户的请求
          const {data: res} = await this.$http.post('users', this.addForm)
          if (res.meta.status !== 201) return this.$message.error('添加用户失败')
          this.$message.success('添加用户成功')
          this.addDialogVisible = false
          this.getUsersList()//重新获取用户列表

        })
      },
      //点击确认，发起编辑用户请求
      editReady() {
        this.$refs.editForm.validate(async valid => {
          if (!valid) return
          //成功  发起添加用户的请求
          const {data: res} = await this.$http.put(`users/${this.editForm.id}`, this.editForm)
          if (res.meta.status !== 200) return this.$message.error('修改用户失败')
          this.$message.success('修改用户成功')
          this.EditdialogVisible = false
          this.getUsersList()//重新获取用户列表

        })
      },
      async showEdit(id) {
        //通过id查询用户信息
        const {data: res} = await this.$http.get(`users/${id}`)
        if (res.meta.status !== 200) return this.$message.error('查询用户信息失败')
        this.editForm = res.data
        this.EditdialogVisible = true
      },
      async editDelete(id) {
        const configresult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        //如果为点击确定 返回configresult为confirm字符串   取消则返回cancel字符串
        if (configresult !== 'confirm') {
          return this.$message.info('已经取消了删除')
        } else {
          //发起删除该行用户信息
          const {data: res} = await this.$http.delete('users/' + id)
          if (res.meta.status !== 200) return this.$message.error('删除用户失败')
          this.$message.success('删除用户成功')
          //删除成功 重新查询信息
          this.getUsersList()
        }
      },
      //分配权限按钮的点击
      async setRoleRights(userInfo){
        this.userInfo = userInfo
        //获取所有角色列表的数据
        const {data: res} = await this.$http.get('roles')
        if (res.meta.status !== 200)  return
        this.rolesList = res.data
        this.setRoleDialogVisible = true
        console.log(this.rolesList);
      },
      //分配角色的确认点击事件
      async setRoleClick(){
        if (!this.selectRoleId){this.$message.error('请选择要分配的用户角色')}
         const {data:res} = await this.$http.put(`users/${this.userInfo.id}/role`,
           {rid: this.selectRoleId})
        if (res.meta.status !== 200) return  this.$message.error('角色分配失败')
        this.$message.success('角色分配成功')
        this.getUsersList();
        this.setRoleDialogVisible = false


      }

    },
    created() {
      this.getUsersList();
    }
  }
</script>

<style lang="less" scoped>
    .el-button {
        margin-left: 10px;
    }

</style>